package com.example.myapplicationktkt2.notification

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.util.Log
import androidx.core.content.ContextCompat
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner

class AppLifecycleObserver(private val context: Context) : DefaultLifecycleObserver {
    private var lastNotificationTime: Long = 0
    private val notificationInterval: Long = 1000 // 1秒内不重复发送通知

    override fun onStop(owner: LifecycleOwner) {
        // 添加日志记录，便于调试
        Log.d("AppLifecycleObserver", "App moved to background")

        // 检查通知权限 (Android 13+需要)在 Android 13 (API 33) 及以上版本中，应用需要获得运行时权限才能发送通知，但代码中没有检查这个权限。
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(
                    context,
                    Manifest.permission.POST_NOTIFICATIONS
                ) != PackageManager.PERMISSION_GRANTED) {
                Log.d("AppLifecycleObserver", "Notification permission not granted")
                return
            }
        }

        // 避免短时间内重复发送通知
        val currentTime = System.currentTimeMillis()
        if (currentTime - lastNotificationTime > notificationInterval) {
            // 应用退到后台
            NotificationHelper.sendNotification(context, "为了您的账户安全，程序已进入后台运行")
            lastNotificationTime = currentTime
            Log.d("AppLifecycleObserver", "Notification sent")
        } else {
            Log.d("AppLifecycleObserver", "Notification skipped to avoid duplication")
        }
    }

    override fun onStart(owner: LifecycleOwner) {
        // 应用回到前台
        Log.d("AppLifecycleObserver", "App moved to foreground")
    }
}